package com.musicstore.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.musicstore.dao.GenreDao;
import com.musicstore.dao.MyBatisUtil;
import com.musicstore.entity.Genre;

public class GenreDaoImpl implements GenreDao {

	public List<Genre> getAll() {
		SqlSession session=null;
		try {
			session =MyBatisUtil.openSession();
			GenreDao genreDao =session.getMapper(GenreDao.class);
			return genreDao.getAll();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session!=null){
				session.close();
			}
		}
		return null;
	}

	public Genre fetchById(int id) {
		SqlSession session=null;
		try {
			session=MyBatisUtil.openSession();
			Genre genre=session.getMapper(GenreDao.class).fetchById(id);
			return genre;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(session!=null){
				session.close();
			}
		}
		return null;
	}

	public boolean delete(int id) {
		SqlSession session=null;
		boolean bool=false;
		try {
			session =MyBatisUtil.openSession();
			session.getMapper(GenreDao.class).delete(id);
			session.commit();
			bool=true;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			bool=false;
		} finally {
			if(session!=null){
				session.close();
			}
			
		}
		return bool;
	}
	
	public static void main(String[] args) {
		GenreDaoImpl gImpl =new GenreDaoImpl();
		System.out.println(gImpl.delete(10));
	}
	
	public boolean add(Genre genre) {
		SqlSession session=null;
		boolean bool=false;
		try {
			session =MyBatisUtil.openSession();
			session.getMapper(GenreDao.class).add(genre);
			session.commit();
			bool=true;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			bool=false;
		} finally {
			if(session!=null){
				session.close();
			}
		}
		return bool;
	}

	public boolean update(Genre genre) {
		SqlSession session=null;
		boolean bool=false;
		try {
			session =MyBatisUtil.openSession();
			session.getMapper(GenreDao.class).update(genre);
			session.commit();
			bool=true;
		} catch (Exception e) {
			e.printStackTrace();
			session.rollback();
			bool=false;
		} finally {
			if(session!=null){
				session.close();
			}
		}
		return bool;
	}

}
